package best.driver.android.common.model;

import best.driver.android.common.app.AppProxyFactory;
import best.driver.android.common.network.ApiRequest;
import best.driver.android.common.network.BestError;

public abstract class HttpRequestModel extends AbstractModel {

    private ApiRequest<?> mApiRequest;

    @Override
    public void loadData() {
        super.loadData();

        if (mApiRequest != null) {
            mApiRequest.cancel();
            mApiRequest = null;
        }

        mApiRequest = onCreateLoadDataRequest();
        mApiRequest.setListener(new ApiRequestListenerImpl());
        AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(mApiRequest);
    }

    @Override
    public void cancelLoad() {
        super.cancelLoad();
        if (mApiRequest != null) {
            mApiRequest.cancel();
            mApiRequest = null;
        }
    }

    protected abstract ApiRequest onCreateLoadDataRequest();

    protected void onLoadSuccess(Object response) {
        mApiRequest = null;
        notifyModelFinishLoad();
    }

    protected void onLoadFailed(BestError error) {
        mApiRequest = null;
        notifyModelLoadFailed(error);
    }

    private class ApiRequestListenerImpl implements ApiRequest.ApiRequestListener {

        @Override
        public void onRequestSuccess(Object response) {
            onLoadSuccess(response);
        }

        @Override
        public void onRequestError(BestError error) {
            onLoadFailed(error);
        }
    }
}
